package com.itheima.datastructure.demo1;

import java.util.Arrays;
public class MaxProduct {
    public static void main(String[] args) {
        int[] nums = {-10, -3, 5, 6};
        System.out.println(calculateMaxProduct(nums));
    }

    public static int calculateMaxProduct(int[] nums) {
        if (nums == null || nums.length < 3) {
            throw new IllegalArgumentException("Input array must contain at least three elements and cannot be null.");
        }

        // Find the three largest and two smallest numbers in one pass
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;

        for (int x : nums) {
            if (x < min1) {
                min2 = min1;
                min1 = x;
            } else if (x < min2) {
                min2 = x;
            }

            if (x > max1) {
                max3 = max2;
                max2 = max1;
                max1 = x;
            } else if (x > max2) {
                max3 = max2;
                max2 = x;
            } else if (x > max3) {
                max3 = x;
            }
        }

        return Math.max(min1 * min2 * max1, max1 * max2 * max3);
    }
}
